//
//  YLAppDelegate.m
//  xpkc
//
//  Created by wanmeizty on 14-8-16.
//  Copyright (c) 2014年 wanmeizty. All rights reserved.
//

#import "YLAppDelegate.h"
#import "YLCustomNavigationController.h"
#import "YLCustomTabBarController.h"
#import "ListenTestViewController.h"
#import "ListenTestCatalogueViewController.h"
#import "CourseViewController.h"
#import "OffLineViewController.h"
#import "HomeViewController.h"
#import "OpenCourseViewController.h"
#import "UserCenterViewController.h"
#import "IntroductionView.h"
#import <sys/xattr.h>
#import <AlipaySDK/AlipaySDK.h>

@implementation YLAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
    NewsViewController *newsVC = [[NewsViewController alloc] init];
    YLCustomNavigationController *navHomeVC = [[YLCustomNavigationController alloc] initWithRootViewController:newsVC];
    //opencourse
    OpenCourseViewController *openVC = [[OpenCourseViewController alloc]init];
    YLCustomNavigationController *navOpenVC = [[YLCustomNavigationController alloc]initWithRootViewController:openVC];
    //ocursecenter
    CourseCenterViewController *center = [[CourseCenterViewController alloc]init];
    YLCustomNavigationController *navCenter = [[YLCustomNavigationController alloc]initWithRootViewController:center];
    //mycourse
    CourseViewController *course = [[CourseViewController alloc] init];
    YLCustomNavigationController *navCourse = [[YLCustomNavigationController alloc] initWithRootViewController:course];
    //usercenter
    UserCenterViewController *user = [[UserCenterViewController alloc] init];
    YLCustomNavigationController *navUser = [[YLCustomNavigationController alloc] initWithRootViewController:user];
    
    YLCustomTabBarController *customTab = [[YLCustomTabBarController alloc] init];
    NSArray *viewC = @[navHomeVC,navOpenVC,navCenter,navCourse,navUser];
    customTab.viewControllers = viewC;
    [self addSkipBackupAttributeToPath:DOC_PATH];
    self.window.rootViewController = customTab;
    
    self.window.backgroundColor = [UIColor lightGrayColor];
    [self.window makeKeyAndVisible];
    [application setStatusBarHidden:YES withAnimation:UIStatusBarAnimationNone];
    [application setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
    [application setStatusBarStyle:UIStatusBarStyleLightContent];
    
    [self launchCheck];
    NSSetUncaughtExceptionHandler(&UncaughtExceptionHandler);
    return YES;
    
    
    
    
    self.drmServer = [[DWDrmServer alloc] initWithListenPort:20140];
    [self.drmServer start];
}

/**
 *  启动检测
 */
- (void)launchCheck{
    logdebug(@"启动");
    NSString *appVerision =
    [[NSUserDefaults standardUserDefaults]valueForKey:@"appVersion"];
    
    if (appVerision.length == 0) {
        appVerision = @"1.0.0";
    }
    NSArray *array = [appVerision componentsSeparatedByString:@"."];
    
    int oldVer = [[array objectAtIndex:0]intValue]*100*100+[[array objectAtIndex:1]intValue]*100+[[array objectAtIndex:2]intValue];
    
    NSDictionary *appdic = [[NSBundle mainBundle] infoDictionary];
    
    NSString *curVersion = [appdic objectForKey:@"CFBundleShortVersionString"];
    NSArray *array2 = [curVersion componentsSeparatedByString:@"."];
   
    
    int curVer = [[array2 objectAtIndex:0]intValue]*100*100+[[array2 objectAtIndex:1]intValue]*100+[[array objectAtIndex:2]intValue];
    
    //FIXME:测试数据，发布注意修改   应为!
    if (oldVer != curVer) {//oldVer != curVer
        //大版本更新会有引导页显示   应为!
        logdebug(@"新版本");
        if (oldVer/100 != curVer/100) {//oldVer/100 != curVer/100
            //添加引导页
            IntroductionView *introducView = [[IntroductionView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
            [[NSUserDefaults standardUserDefaults] setObject:@{} forKey:@"defaultAddressKey"];
            introducView.isNotIntroduction = NO;
            [self.window addSubview:introducView];
        }
        //保存当前版本号
        [[NSUserDefaults standardUserDefaults]setValue:curVersion forKey:@"appVersion"];
        [[NSUserDefaults standardUserDefaults]synchronize];
        //写入bundle
        [self SettingsBundle:curVersion];
    }
    //========bug提交
    if ([[NSFileManager defaultManager]fileExistsAtPath:BUGLOG_PATH]) {
        //
        NSString *buginfo = [NSString stringWithContentsOfFile:BUGLOG_PATH encoding:NSUTF8StringEncoding error:nil];
        
        //@"http://www.studypay.com/MAPI/index.php/Setting/feedBack";
        NSString *timeString = [NSString stringWithFormat:@"%@", [GetTime getTime]];
        NSString *string = [NSString stringWithFormat:@"/Setting/feedBack/key/0b6f2f666ddfd0e56e4d566f12a0f353/time/%@", timeString];
        NSString *MD5string = [string md5];
        NSString *urlString = [NSString stringWithFormat:@"http://www.studypay.com/MAPI/index.php/Setting/feedBack/hash/%@/appid/1", MD5string];
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        NSString *username = [[NSUserDefaults standardUserDefaults]valueForKey:USERNAME_REMBER];
        NSDictionary *paramters = [NSDictionary dictionaryWithObjectsAndKeys:timeString,@"time",username,@"username",buginfo,@"msg", nil];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        [manager POST:urlString parameters:paramters success:^(AFHTTPRequestOperation *operation, id responseObject) {
            //成功
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
            logdebug(@"bugpost--%@",dic);
            [[NSFileManager defaultManager]removeItemAtPath:BUGLOG_PATH error:nil];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            //失败
            logdebug(@"%@",error.localizedDescription);
        }];
    }else{
        return;
    }
}
/**
 *  异常捕获
 *
 *  @param exception 异常
 */
void UncaughtExceptionHandler(NSException *exception){
    NSArray *arr = [exception callStackSymbols];//得到当前调用栈信息
    NSString *reason = [exception reason];//非常重要，就是崩溃的原因
    NSString *name = [exception name];//异常类型
    NSString *crashLogInfo = [NSString stringWithFormat:@"exception type : %@ \n crash reason : %@ \n call stack info : %@", name, reason, arr];
    NSString *deveiceInfoStr = [GetPhoneInfo getBaseInfo];
    NSString *username = [[NSUserDefaults standardUserDefaults]valueForKey:USERNAME_REMBER];
    //发送的详情
    NSString *postInfo = [NSString stringWithFormat:@"iOS异常报告--Time:%@\n用户详情:%@\n%@\n错误详情:\n%@",[GetTime getYYMMDDWithDate2:[NSDate date]],username,deveiceInfoStr,crashLogInfo];
    logdebug(@"%@",postInfo);
    logdebug(@"保存bug%d",
             [postInfo writeToFile:BUGLOG_PATH atomically:YES encoding:NSUTF8StringEncoding error:nil]);
    //发邮件
    NSString *urlStr = [NSString stringWithFormat:@"mailto://1690611805@qq.com?subject=提交异常报告&body=感谢您的配合!\n%@",postInfo];
    NSURL *url = [NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    [[UIApplication sharedApplication] openURL:url];
    
}
/**
 *  设置SettingBundle
 */
- (void)SettingsBundle:(NSString *)curVersion{
    NSString *settingsBundle = [[NSBundle mainBundle] pathForResource:@"Settings" ofType:@"bundle"];
    if(!settingsBundle) {
        NSLog(@"Could not find Settings.bundle");
        return;
    }
   // NSLog(@"----%@",settingsBundle);
    NSMutableDictionary *settings = [NSMutableDictionary  dictionaryWithContentsOfFile:[settingsBundle stringByAppendingPathComponent:@"Root.plist"]];
    //NSLog(@"%@",settings);
    NSMutableArray *preference = [NSMutableArray arrayWithArray:[settings objectForKey:@"PreferenceSpecifiers"]];
    NSMutableDictionary *versionDic = [NSMutableDictionary dictionaryWithDictionary:[preference objectAtIndex:1]];
    //程序的
    [versionDic setObject:curVersion forKey:@"DefaultValue"];
    [preference replaceObjectAtIndex:1 withObject:versionDic];
    [settings setObject:preference forKey:@"PreferenceSpecifiers"];
    //FIXME:写入成功，但是重启无效，待定
    logdebug(@"%d",
             [settings writeToFile:[settingsBundle stringByAppendingPathComponent:@"Root.plist"] atomically:YES]);
}
/**
 *  设置docment不同步
 *
 *  @param path 路径
 */
- (void)addSkipBackupAttributeToPath:(NSString*)path {
    u_int8_t b = 1;
    setxattr([path fileSystemRepresentation], "com.apple.MobileBackup", &b, 1, 0, 0);
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    //程序进入后台的时候将drmServer停止
    logdebug(@"挂起");
    [self.drmServer stop];
    //发送通知保存下载信息
    [[NSNotificationCenter defaultCenter]postNotificationName:SAVE_DATA_WHEN_EXIT object:nil];
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    logdebug(@"进入后台");
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    logdebug(@"返回前台");
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    logdebug(@"复原");
    //程序进入活跃的时候启动drmServer服务并设置端口
    [[NSNotificationCenter defaultCenter] postNotificationName:@"change1" object:nil];
    self.drmServer = [[DWDrmServer alloc] initWithListenPort:20140];
    BOOL success = [self.drmServer start];
    if (!success) {
        logdebug(@"drmServer 启动失败");
    }
    
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    [[NSNotificationCenter defaultCenter]postNotificationName:SAVE_DATA_WHEN_EXIT object:nil];
    logdebug(@"终止");
    
    [self.drmServer stop];
}


/**
 *  禁止转屏
 *
 *  @param application <#application description#>
 *  @param window      <#window description#>
 *
 *  @return <#return value description#>
 */
//-(NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{
//    return UIInterfaceOrientationMaskPortrait;
//}





- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {
    
    
    if ([url.host isEqualToString:@"safepay"]) {
        
        //         [[AlipaySDK defaultService] processAuth_V2Result:url
        //                                       standbyCallback:^(NSDictionary *resultDic) {
        //          NSLog(@"result = %@",resultDic);
        //          NSString *resultStr = resultDic[@"result"];
        //        }];
        //如果极简 SDK 不可用,会跳转支付宝钱包进行支付,需要将支付宝钱包的支付结果回传给 SDK if ([url.host isEqualToString:@"safepay"]) {
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
        }];
    }
    if ([url.host isEqualToString:@"platformapi"]){//支付宝钱包快登授权返回 authCode
        [[AlipaySDK defaultService] processAuthResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
        }];
    }
    
    return YES;
}









@end
